package cn.yitun.chat.yitunserverimapicore.business.chat.service.impl;

import cn.yitun.chat.yituncommonmessage.ExceptionEnum;
import cn.yitun.chat.yituncommonmessage.result.ResultMessage;
import cn.yitun.chat.yituncommonutil.YitunCollectionUtil;
import cn.yitun.chat.yituncommonutil.YitunMapUtil;
import cn.yitun.chat.yitunservercommonlib.crud.yitun.CrudServiceImpl;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.base.chat.ChatItem;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.core.chat.GroupChatHistory;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.group.GroupChatContentDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.po.group.GroupChatContentInfo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.group.GroupChatContentVo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.system.user.UserVo;
import cn.yitun.chat.yitunservercommonlib.enums.userChat.UserChatTypeEnums;
import cn.yitun.chat.yitunservercommonlib.util.NumUtil;
import cn.yitun.chat.yitunservercommonlib.util.R;
import cn.yitun.chat.yitunserverimapicore.business.chat.service.GroupChatHistoryService;
import cn.yitun.chat.yitunserverimbase.dao.group.GroupChatContentDao;
import cn.yitun.chat.yitunserverimcore.general.main.biz.chat.manager.GroupChatHistoryManager;
import cn.yitun.chat.yitunserverimcore.general.main.biz.chat.manager.GroupChatManager;
import cn.yitun.chat.yitunserverimcore.general.main.biz.userchat.manager.UserManager;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * Date 2019-03-08 13:48:52<br>
 * Description
 *
 * @author yitun<br>
 * @version 1.1
 */
@Service
@Slf4j
public class GroupChatHistoryServiceImpl
		extends CrudServiceImpl<GroupChatContentDao, GroupChatContentDto, GroupChatContentInfo, GroupChatContentVo>
		implements GroupChatHistoryService {

	@Resource
	GroupChatHistoryManager groupChatHistoryManager;
	@Resource
	private UserManager userManager;
	@Resource
	private GroupChatManager groupChatManager;

	/**
	 * 根据记录表id查询用户聊天记录（上翻，下拉方式的）
	 * @param query
	 * @return
	 */
	public ResultMessage getListByStartId(GroupChatContentDto query) {

		String direction = query.getDirection();
		Long groupId = query.getGroupId();
		Long startId = query.getStartId();
		int currentPageNo = query.getCurrentPageNo();
		int pageSize = query.getPageSize();
		boolean latest = !"history".equals(direction);

		List<GroupChatHistory> contents = new ArrayList<>();

		if ((null != groupId && !"".equals(groupId))) {

			GroupChatContentVo ucc = null;
			if (null != startId && !"".equals(startId)) {
				ucc = dao.getVO(startId);
			}
			Long times = ucc.getUpdateTime();
			PageHelper.startPage(currentPageNo, pageSize);
			List<GroupChatContentVo> chatContentList = dao.listVO(R.param("groupId", groupId).put("latest", latest).put("times", times));
			contents = groupChatHistoryManager.getGroupChatHistoryList(chatContentList, true);
		}

		Map<String, Object> page = new HashMap<>();
		page.put("direction", latest ? "latest" : "history");

		ResultMessage m = new ResultMessage();
		m.bodyPut("groupId", groupId);
		m.bodyPut("contents", contents);
		m.bodyPut("page", page);
		return m;
	}

	/**
	 * 根据消息id查询用户聊天记录（上翻，下拉方式的）
	 * @param query
	 * @return
	 */
	public ResultMessage getListByStartMessageKey(GroupChatContentDto query) {
		String direction = query.getDirection();
		Long groupId = query.getGroupId();
		Long startMessageId = query.getMessageId();
		boolean latest = UserChatTypeEnums.CHAT_DIRECTION_BEFORE.getType().equals(direction);
		List<GroupChatHistory> contents = new ArrayList<>();

		if (NumUtil.isValid(groupId)) {

			GroupChatContentVo ucc = null;
			if (NumUtil.isValid(startMessageId)) {
				ucc = dao.getVOByMessageId(groupId, startMessageId);
			}

			long times = System.currentTimeMillis();
			if (null != ucc && ucc.getUpdateTime() > 0) {
				times = ucc.getUpdateTime();
			}
			List<GroupChatContentVo> chatContentList = dao.selGroupChatContentList(query.getGroupId(), query.getId(), query.getMessageId(), latest, times, query.getSearchNum());
			contents = groupChatHistoryManager.getGroupChatHistoryList(chatContentList, true);
		}

		ResultMessage rm = new ResultMessage();
		rm.bodyPut("list", contents);
		rm.bodyPut("groupId", groupId);
		rm.bodyPut("direction", latest ? UserChatTypeEnums.CHAT_DIRECTION_AFTER.getType() : UserChatTypeEnums.CHAT_DIRECTION_BEFORE.getType());
		return rm;
	}

	/**
	 * 获取群聊天记录
	 * @param chatQuery
	 * @return
	 */
	public ResultMessage queryGroupChatContentList(GroupChatContentDto chatQuery) {
		ResultMessage m = new ResultMessage();

		if (chatQuery.getGroupId() == null) {
			m.addError(ExceptionEnum.LOSE_FILED);
			return m;
		}

		Long groupId = chatQuery.getGroupId();
//		GroupChatLogDto groupChatLogQuery = new GroupChatLogDto();
//		groupChatLogQuery.setGroupId(groupId);
//		groupChatLogQuery.setText(chatQuery.getText());
//		groupChatLogQuery.setBegin(chatQuery.getBegin());
//		groupChatLogQuery.setEnd(chatQuery.getEnd());
//		groupChatLogQuery.setContentIds(chatQuery.getContentIds());

		boolean hasGroupId = null == groupId;
		List<GroupChatContentVo> chatContentList = dao.listVO(YitunMapUtil.java2Map(chatQuery, false));
		List<GroupChatHistory> contents = hasGroupId ? new ArrayList<>() : groupChatHistoryManager.getGroupChatHistoryList(chatContentList, true);

		m.bodyPut("groupId", groupId);
		m.bodyPut("contents", contents);
		return m;
	}

	/**
	 * 根据记录获取聊天记录
	 * @param chatQuery
	 * @return
	 */
	@Override
	public ResultMessage queryByContentIds(GroupChatContentDto chatQuery) {
		ResultMessage m = new ResultMessage();

		//处理传入空参的情况
		if (YitunCollectionUtil.isEmpty(chatQuery.getIds())) {
			m.bodyPut("list", new ArrayList<>());
			return m;
		}

		List<GroupChatContentVo> chatContentList = dao.listVO(YitunMapUtil.java2Map(chatQuery, false));
		List<GroupChatHistory> contents =  groupChatHistoryManager.getGroupChatHistoryList(chatContentList, true);

		m.bodyPut("list", contents);

		return m;
	}

	/**
	 * 添加聊天记录历史
	 * @param groupId
	 * @param userId
	 * @param messageId
	 * @param chatItemList
	 */
	public void addGroupChatHistory(
			Long groupId,
			Long userId,
			Long messageId,
			List<ChatItem> chatItemList) {
		UserVo userData = userManager.getUserDataById(userId);
		groupChatManager.addGroupChatHistory(userData, messageId, groupId, chatItemList);
	}


}
